#include <string.h>
#include <stdio.h>
#include <stdlib.h>

/*
 * 不是标准，GNU C中可用
 *
 * 分割字符串
 *
 *	strsep使用传入的参数来确定字符串的起始位置，是可重入的，也是Linux kernel推荐的函数，strtok的替代品。
 */


int strsep1(void)
{
	char   ptr[] = { "abcdefghijklmnopqrstuvwxyz "}; 
	char   *p, *needle = "m "; 

	p = ptr; 
	printf( "%s\n ", strsep(&p, needle));	/* abcdefghijkl */
	printf( "%s\n ", p);					/*  nopqrstuvwxyz*/
	
	needle= "s "; 
	printf( "%s\n ", strsep(&p, needle));	/*  nopqr */
	printf( "%s\n ", p);					/*  tuvwxyz */

    return 0;
}

int strsep2(void)
{
	char str[] = "root:x::0:root:/root:/bin/bash:";
	char *buf;
	char *token;

	buf = str;
	while((token = strsep(&buf, ":")) != NULL){
		printf("%s\n", token);
	}
	return 0;
}

void gga()
{
	char * pstr = NULL;
	char gga_rmc[] = {"\r\n$GNRMC,082935.000,A,2307.335517,N,11320.737380,E,0.000,0.00,010221,,E,A*09\r\n$GNGGA,082935.000,2307.335517,N,11320.737380,E,1,15,0.83,66.504,M,0,M,,*6E\r\n"};
	char *needle = "\r\n";
	char *result[8];
	int i = 0;

	pstr = gga_rmc;

	while((result[i] = strsep(&pstr, needle)) != NULL) {
		printf("result[%d] = %s len = %ld\n", i, result[i], strlen(result[i]));
		i++;
	}
}

int fetch_gga(char * src, char * des)
{
	char * pstr = NULL;
	char *needle = "\r\n";
	char *result[8];
	int i = 0, len = 0;

	pstr = src;

	while((result[i] = strsep(&pstr, needle)) != NULL) {
		printf("result[%d] = %s, len = %ld\n", i, result[i], strlen(result[i]));
		i++;
	}

	len = strlen(result[4]);
	if (len > 16) {
		strncpy(des, result[4], len);
		return 0;
	}
	else
		return -1;
}

void test_gga()
{
	char gga_rmc[] = {"\r\n$GNRMC,082935.000,A,2307.335517,N,11320.737380,E,0.000,0.00,010221,,E,A*09\r\n$GNGGA,082935.000,2307.335517,N,11320.737380,E,1,15,0.83,66.504,M,0,M,,*6E\r\n"};
	char *needle = "\r\n";
	char gga[128] = {0};
	char *pgga = gga;

	/* obtain gga */
	if (!fetch_gga((char *)gga_rmc, pgga)) {
		printf("gga = %ld:%s\n", strlen(pgga), pgga);
	}
}

int main()
{
	//strsep1();
	//strsep2();
	//gga();
	test_gga();

	return 0;
}
